package com.geek.factory.security;

import cn.hutool.core.collection.CollectionUtil;
import com.geek.factory.entity.Role;
import com.geek.factory.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/7/7
 * <p>
 * LoginUser  认证主体，重写UserDetails需要的用户信息
 * 自定义LoginUser作为SpringSecurity返回的管理员信息实体类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    public LoginUser(User user) {
        this.user = user;
    }

    //权限
    private List<SimpleGrantedAuthority> authorities;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtil.isNotEmpty(authorities)) {
            return authorities;
        }

        authorities = new ArrayList<>();
        Set<Role> roles = user.getRoles();

        for (Role role : roles) {
            // 使用角色名作为权限标识（确保非空）
            String authority = "ROLE_" + role.getRoleName();  // 添加ROLE_前缀符合Spring Security规范
            if (StringUtils.hasLength(authority)) {
                authorities.add(new SimpleGrantedAuthority(authority));
            }
        }

        // 如果角色为空，至少添加一个默认权限
        if (authorities.isEmpty()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_DEFAULT"));
        }

        return authorities;
    }


    //密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    //账户
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    //判断当前账户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //判断当前账户是否锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //判断当前账户认证是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //判断当前账户是否可用 1可用 0不可用
    @Override
    public boolean isEnabled() {
        return user.getStatus() == 1;
    }
}
